<?php

namespace app\myr\controller;
use app\wechat\service\JwtService;
use Decimal\Decimal;
use think\admin\Controller;
use think\Request;
use think\facade\Db;
use think\Validate;
use app\myr\model\Jxs as JxsModel;
use app\myr\model\Area as AreaModel;
use think\admin\helper\QueryHelper;

/**
 * 经销商管理
 */
class Jxs extends Controller
{
    
    //默认密码
    protected $default_pwd = '12345678';
    //密码盐
    protected $slat = 'wissun';
      /**
     * 经销商列表
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function index(){
       JxsModel::mQuery()->layTable(function () {
            $this->title = '经销商管理';
        }, static function (QueryHelper $query) {
            $query->like("user_code,username,nickname,role");
        });
    }
    /**
     * 列表数据处理
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(&$data)
    {
        foreach ($data as &$vo) {
            $vo["province"]=$this->get_area_value($vo["province"]);
            $vo["city"]=$this->get_area_value($vo["city"]);
            $vo["district"]=$this->get_area_value($vo["district"]);
            $vo["role_name"]=$vo["role"];
            if($vo["role"] == "1"){
                $vo["role_name"]="省代";
            }else if($vo["role"] == "2"){
                $vo["role_name"]="经销商";
            }else if($vo["role"] == "3"){
                $vo["role_name"]="分销商";
            }else if($vo["role"] == "4"){
                $vo["role_name"]="门店";
            }else if($vo["role"] == "0"){
                $vo["role_name"]="国代";
            }
            $vo["parent_name"]=$this->get_parent_value($vo["parent_id"]);
            if(empty($vo["parent_name"])){
                $vo["parent_name"]="--";
            }
        }
    }
    
    public function get_parent_value($code=""){
        return JxsModel::where("id",$code)->value("username");
    }
    
    public function get_area_value($code=""){
        return AreaModel::where("area_code",$code)->value("name");
    }
    
      /**
     * 经销商添加
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function add(){
        $pid=input("pid",0);
        $parents=JxsModel::select();
        $this->assign("parents",$parents);
        $province=AreaModel::order("id desc")->where("parent_code",0)->select();
        
        $this->assign("parent_id",$pid);
        $this->assign("province",$province);
        $this->set_add_time=date("Y-m-d H:i:s");
        JxsModel::mForm('form');
    }
    
    
    
     /**
     * 经销商修改
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function edit(){
        $id=input("id",0);
        $ids=JxsModel::where("parent_id",$id)->column("id");
        $parents=JxsModel::where("id",'<>',$id);
        foreach ($ids as $kk=>$vv){
            $parents->where("id",'<>',$vv);
        }
        $this->assign("parents",$parents->select());
        $province=AreaModel::order("id desc")->where("parent_code",0)->select();
        $this->assign("province",$province);
        $this->set_add_time=date("Y-m-d H:i:s");
        JxsModel::mForm('form');
    }
    
    //设置经营范围
    protected function _form_filter(array &$vo)
    {
        if ($this->request->isPost()) {
            $data=$this->request->post();
            if($this->request->action() == "add"){
                $where["username"]=$data["username"];
                $is=JxsModel::where($where)->find();
				$uniacid=session("user.uniacid");
				$username=session("user.username");
				if(empty($data["province"])){
				    $this->error("请选择省份");
				}
				if(empty($data["city"])){
				    $this->error("请选择城市");
				}
				if(empty($data["district"])){
				    $this->error("请选择区县");
				}
                if(empty($is)){
                    $curr_user_code=JxsModel::where("user_code","like","%".date("Ymd")."%")->order("user_code desc")->value("user_code");
                    if($curr_user_code){
                        $user_code=$curr_user_code+1;
                    }else{
                        $user_code=date("Ymd")."001";
                    }
                    $vo["add_time"]=date("Y-m-d H:i:s");
                    $vo["uniacid"]=$uniacid;
					$vo["user_code"]=$user_code;
                }else{
                    $this->error("账号已存在");
                }
            }else if($this->request->action() == "edit"){
                if(empty($data["province"])){
				    $this->error("请选择省份");
				}
				if(empty($data["city"])){
				    $this->error("请选择城市");
				}
				if(empty($data["district"])){
				    $this->error("请选择区县");
				}
                //$where["username"]=$data["username"];
               // SystemUser::where($where)->update($data);
            }
        }
        else{
            if(!isset($vo["role"])){
                $vo["role"]=1;
                $vo["province"]="";
                $vo["city"]="";
                $vo["district"]="";
                $this->assign("city","");
                $this->assign("district","");
            }
            if(isset($vo["province"])){
                if($vo["province"]){
                    $city=AreaModel::order("id desc")->where("parent_code",$vo["province"])->select();
                    $this->assign("city",$city);
                }
            }else{
                 $this->assign("city","");
            }
            
            if($this->request->action() == "add"){
                $pid=input("pid",0);
                if($pid){
                    $vo["parent_id"]=$pid;
                }else{
                    $vo["parent_id"]=0;
                }
            }
           
            if(isset($vo["city"])){
                if($vo["city"]){
                    $district=AreaModel::order("id desc")->where("parent_code",$vo["city"])->select();
                    $this->assign("district",$district);
                }
            }else{
                  $this->assign("district","");
            }
        }
    }
    
     /**
     * 重置密码
     * @auth true
     */
    public function reloadpass()
    {
        $data["password"]="123456";
        $field="password";
        $where["id"]=input("id");
        JxsModel::mSave($data, $field, $where);
    }
    
      /**
     * 经销商删除
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function remove()
    {
		if ($this->request->isPost()) {
            $data=$this->request->post();
			$uu=JxsModel::where("id",$data["id"])->find();
			$where["username"]=$uu["username"];
			$is=JxsModel::where($where)->find();
			if($is){
				JxsModel::where($where)->delete();
			}
		}
        JxsModel::mDelete();
    }
    
    //获取城市
    public function ajax_city(){
        if ($this->request->isGet()) {
            $data=$this->request->get();
            $pinvince=AreaModel::order("pinyin asc")->where("parent_code",$data["id"])->select();
            echo json_encode($pinvince);
        }
    }
    
    /**
     * 经销商修改账号密码
     */
    public function change_pwd()
    {
        $param = $this->request->param();
        $validate = new Validate([
            'old_pwd' => 'require',
            'new_pwd' => 'require|confirm:new_pwd_re|length:8|alphaNum',
            'new_pwd_re' => 'require|confirm:new_pwd|length:8|alphaNum'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }
        $jxs_code = $this->request->param('payload')['jxs_code'];
        $account = Db::name('sc_jxs_account')->where(['jxs_code' => $jxs_code, 'password' => md5($param['old_pwd'] . $this->slat)])->find();
        if (!$account) {
            return json(['code' => 0, 'msg' => '原密码错误']);
        }
        if ($param['old_pwd'] == $param['new_pwd']) {
            return json(['code' => 0, 'msg' => '新密码不能与原密码相同']);
        }

        $res = Db::name('sc_jxs_account')->where(['jxs_code' => $jxs_code])->update(['password' => md5($param['new_pwd'] . $this->slat)]);
        if ($res) {
            return json(['code' => 1, 'msg' => '密码修改成功']);
        } else {
            return json(['code' => 0, 'msg' => '密码修改失败']);
        }
    }
    
     /**
     * 经销商积分管理
     */
    public function jxsintegral()
    {
        
        if ($this->request->isPost()) {
            $data=$this->request->post();
            $jxs=JxsModel::where("id",$data["id"])->find();
            if($data["actions"] == 1){
                $uu=JxsModel::where("id",$data["id"])->inc("jxs_integral",$data["act_integral"])->update();
                if($uu){
                    $adddata["source_type"]=$data["actions"];
                    $adddata["integral"]=$data["act_integral"];
                    $adddata["user_id"]=$data["id"];
                    $adddata["create_time"]=date("Y-m-d H:i:s");
                    $adddata["before_integral"]=$jxs["jxs_integral"];
                    $adddata["after_integral"]=$jxs["jxs_integral"]+$data["act_integral"];
                    $adddata["remark"]=$data["remark"];
                    $username=session("user.username");
                    $adddata["admin"]=$username;
                    Db::name("integral_log")->insert($adddata);
                     return json(['code' => 1, 'msg' => '操作成功']);
                }
            }else if($data["actions"] == 2){
                $uu=JxsModel::where("id",$data["id"])->dec("jxs_integral",$data["act_integral"])->update();
                if($uu){
                    $adddata["source_type"]=$data["actions"];
                    $adddata["integral"]=$data["act_integral"];
                    $adddata["user_id"]=$data["id"];
                    $adddata["create_time"]=date("Y-m-d H:i:s");
                    $adddata["before_integral"]=$jxs["jxs_integral"];
                    $adddata["after_integral"]=$jxs["jxs_integral"]+$data["act_integral"];
                    $adddata["remark"]=$data["remark"];
                    $username=session("user.username");
                    $adddata["admin"]=$username;
                    Db::name("integral_log")->insert($adddata);
                    return json(['code' => 1, 'msg' => '操作成功']);
                }
            }
            return json(['code' => 0, 'msg' => '操作失败']);
		}else{
		    $id=input("id","");
            $vo=JxsModel::where("id",$id)->find();
            $this->assign("vo",$vo);
            $this->assign("actions",1);
            return $this->fetch();
		}
    }
    
       
    private $score_table="scan_qrcode_log_jinbi";
  
   
      /**
     * 销售范围
     * @auth true  # 表示需要验证权限
     * @menu true  # 添加系统菜单节点
     * @login true # 强制登录才可访问
     */
    public function xsarea(){
        return $this->fetch();
    }
  


}
